<?php


namespace App\Services\Admin;


use App\Http\Controllers\Api\RemoteApiRoute;
use App\Models\Asin;
use App\Models\Category;
use App\Models\WtCategory;
use Illuminate\Support\Facades\Http;

class CategoryService
{
    public function __construct()
    {

    }

    /**
     * 获取所有一级分类
     * @param $params
     * @return \Illuminate\Http\Client\Response|\Illuminate\Http\JsonResponse
     */
    public function getCategoryInfo($params){
        $params['parent_id'] = 0;
        if (!isset($params['domainId'])){
            $params['domainId'] = 3; //默认获取德国
        }else{
            $params['domainId'] = (int)$params['domainId'];
        }
        $categories = WtCategory::where($params)->orderBy('name','asc')->get();

        return Success('ok', $categories);
    }

    /**
     * 获取指定月份分类数据
     * @param $params
     * @return \Illuminate\Http\Client\Response|\Illuminate\Http\JsonResponse
     */
    public function getWtCategory($params){
        $where['parent_id'] = 0;
        if (!isset($params['domainId'])){
            $where['domainId'] = 3; //默认获取德国
        }else{
            $where['domainId'] = (int)$params['domainId'];
        }

        $where['month'] = $params['month'];
        $categories = WtCategory::where($where)->orderBy('order_count_total','desc')->get();

        foreach ($categories as $category){
            if ($category->children_num > 0){
                $category->children = [['name' => '']];
            }else{
                $category->children = [];
            }
        }

        return Success('oka', $categories);
    }

    /**
     * 获取月份区间内分类树聚合
     * @param $params
     * @return \Illuminate\Http\JsonResponse
     */
    public function getWtGroupCategory($params){
        $where['parent_id'] = 0;
        if (!isset($params['domainId'])){
            $where['domainId'] = 3; //默认获取德国
        }else{
            $where['domainId'] = (int)$params['domainId'];
        }

        //月份区间
        if (!$params['month_range'] || $params['month_range'] == []) {
            return Error('请选择开始结束日期！');
        }

        //获取月份区间
        $month_range = $params['month_range'];
        $months = showMonthRange($month_range[0], $month_range[1]);
        $where['month'] = ['$in' => $months];

        $pipeline = [
            [
                '$match' => $where
            ],
            [
                '$group' => [
                    '_id' => [
                        'catId' => '$catId',
                    ],
                    'sj_name_total' => ['$max' => '$sj_name_total'],
                    'sku_count_total' => ['$max' => '$sku_count_total'],
                    'order_count_total' => ['$sum' => '$order_count_total'],
                    'name' => ['$last' => '$name'],
                    'children_num' => ['$last' => '$children_num'],
                ],
            ],
            [
                '$sort' => ['order_count_total' => -1]
            ]
        ];
        $results = WtCategory::aggregate($pipeline);

        foreach ($results as $category){
            if ($category->children_num > 0){
                $category->children = [['name' => '']];
            }else{
                $category->children = [];
            }
            $category->catId = $category->_id->catId;
        }
        return Success('oka', $results);
    }

    /**
     * 获取当前分类下级所有分类
     * @param $params
     * @return \Illuminate\Http\Client\Response|\Illuminate\Http\JsonResponse
     */
    public function getCategoryChildren($params){
        $where = ['parent_id' => $params['catId'], 'month' => $params['month']];
        $categories = WtCategory::where($where)->orderBy('order_count_total','desc')->get();
        foreach ($categories as $category){
            if ($category->children_num > 0){
                $category->children = [['name' => '']];
            }else{
                $category->children = [];
            }
        }
        return Success('oka', $categories);
    }

    /**
     * 获取月份区间内子分类的并集
     * @param $params
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCategoryGroupChildren($params){
        //获取月份区间
        $month_range = $params['month_range'];
        $months = showMonthRange($month_range[0], $month_range[1]);
        $where = ['parent_id' => $params['catId'], 'month' => ['$in' => $months]];

        $pipeline = [
            [
                '$match' => $where
            ],
            [
                '$group' => [
                    '_id' => [
                        'catId' => '$catId',
                    ],
                    'sj_name_total' => ['$max' => '$sj_name_total'],
                    'sku_count_total' => ['$max' => '$sku_count_total'],
                    'order_count_total' => ['$sum' => '$order_count_total'],
                    'children_num' => ['$max' => '$children_num'],
                    'name' => ['$last' => '$name'],
                ],
            ],
            [
                '$sort' => ['order_count_total' => -1]
            ]
        ];
        $results = WtCategory::aggregate($pipeline);

        foreach ($results as $category){
            if ($category->children_num > 0){
                $category->children = [['name' => '']];
            }else{
                $category->children = [];
            }
            $category->catId = $category->_id->catId;
        }
        return Success('oka', $results);
    }

    /**
     * 获取子分类
     * @param $params
     * @return \Illuminate\Http\Client\Response|\Illuminate\Http\JsonResponse
     */
    public function getChildrenInfo($params){
        $category = Category::where($params)->first();
        if ($category->childrens){
            $children = explode(',',$category->childrens);
            $categories = WtCategory::whereIn('catId',$children)->get();
        }else{
            return Error('该分类下无子分类！');
        }
        return Success('ok', $categories);
    }

    public function getCategoryProduct($params){
        if (!isset($params['update_time']) || !isset($params['numbers'])){
            return Error('请输入更新时间/获取数量！');
        }
        $time_gte = strtotime($params['update_time'][0]);
        $time_lte = strtotime($params['update_time'][1]);
        $where = ['domainId' => $params['domainId'], 'catId' => $params['catId']];
        $where['create_time'] = ['$gte' => $time_gte, '$lte' => $time_lte];
        $asins = Asin::where($where)->limit($params['numbers'])->get();

        if (!count($asins)){
            $url = env('REMOTE_API_URL') . RemoteApiRoute::CATEGORY_PRODUCT;
            $response = Http::post($url,$params);
            if ($response->ok()){
                Asin::insert($response->json()['result']);
                return $response->json();
            }else{
                return Error($response->reason());
            }
        }
        return Success('ok', $params);
    }

    /**
     * 递归解析菜单结构
     * @param $menu
     * @return array
     */
    private function init_categories($data, $pId)
    {
        $tree = array();
        foreach ($data as $k => $v) {

            if ($v->parent_id == $pId) {
                $children = $this->init_categories($data, $v->catId);
                if ($children){
                    $v->children = $children;
                }

                //排序
                $sort[] = $v->catId;
                $tree[] = $v;
                array_multisort($sort,SORT_NUMERIC,SORT_ASC,$tree);
                unset($data[$k]);
            }
        }
        return $tree;
    }


}
